from os.path import dirname
from OpenSSL.crypto import PKey
from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
from OpenSSL.crypto import dump_privatekey, dump_publickey
from OpenSSL.crypto import sign, verify
from OpenSSL.crypto import X509,Error
from OpenSSL.crypto import load_privatekey,load_certificate,dump_certificate
import base64
pk = PKey()

print(pk)
pk.generate_key(TYPE_RSA, 4096)
dpub = dump_publickey(FILETYPE_PEM, pk)
print(dpub)
dpri = dump_privatekey(FILETYPE_PEM, pk)
print(dpri)



signature = sign(pk, '搜狐新闻hello, world!'.encode("utf8"), 'sha512')
print(base64.b64encode(signature))

x509 = X509()
x509.set_pubkey(pk)
try:
    verify(x509, signature, bytes('搜狐新闻hello, world!', "utf8"), 'sha512')
except :
    print("error!")
else:
    print("pass!")



with open(dirname(__file__)+'/GLBFLH9V.crt','r') as f:
    cert = load_certificate(FILETYPE_PEM,f.read().encode())

with open(dirname(__file__)+'/GLBFLH9V.key','r') as f:
    privkey = load_privatekey(FILETYPE_PEM,f.read().encode())

signature = sign(privkey, b'hello, world!', 'sha256')
print(base64.b64encode(signature))
try:
    verify(cert, signature, b'hello, world!', 'sha256')
except Error as e :
    print((e))
else:
    print("pass!")
